<template>
  <div class="optimization-container">
    <div class="optimization-header">
      <div class="title">参数优化</div>
      <div class="actions">
        <el-select v-model="selectedStrategy" placeholder="选择策略" size="small">
          <el-option label="MA策略" value="ma" />
          <el-option label="网格策略" value="grid" />
          <el-option label="趋势策略" value="trend" />
        </el-select>
        <el-button type="primary" size="small" @click="startOptimization">开始优化</el-button>
      </div>
    </div>

    <div class="optimization-content">
      <div class="param-section">
        <div class="section-row">
          <div class="label">回测周期</div>
          <el-select v-model="backTestPeriod" placeholder="过去30天" size="small">
            <el-option label="过去7天" value="7" />
            <el-option label="过去30天" value="30" />
            <el-option label="过去90天" value="90" />
          </el-select>
        </div>

        <div class="section-row">
          <div class="label">优化目标</div>
          <el-select v-model="optimizationTarget" placeholder="最大收益率" size="small">
            <el-option label="最大收益率" value="maxProfit" />
            <el-option label="最大夏普比" value="maxSharpe" />
            <el-option label="最小回撤" value="minDrawdown" />
          </el-select>
        </div>
      </div>

      <div class="param-section">
        <div class="section-title">优化参数选择</div>
        
        <div class="param-row">
          <div class="param-label">移动平均周期 (快线)</div>
          <div class="param-inputs">
            <el-input v-model="fastMA.min" size="small" placeholder="最小值" />
            <el-input v-model="fastMA.max" size="small" placeholder="最大值" />
            <el-input v-model="fastMA.step" size="small" placeholder="步长" />
            <el-checkbox v-model="fastMA.enabled">启用</el-checkbox>
          </div>
        </div>

        <div class="param-row">
          <div class="param-label">移动平均周期 (慢线)</div>
          <div class="param-inputs">
            <el-input v-model="slowMA.min" size="small" placeholder="最小值" />
            <el-input v-model="slowMA.max" size="small" placeholder="最大值" />
            <el-input v-model="slowMA.step" size="small" placeholder="步长" />
            <el-checkbox v-model="slowMA.enabled">启用</el-checkbox>
          </div>
        </div>

        <div class="param-row">
          <div class="param-label">止损比例</div>
          <div class="param-inputs">
            <el-input v-model="stopLoss.min" size="small" placeholder="最小值" />
            <el-input v-model="stopLoss.max" size="small" placeholder="最大值" />
            <el-input v-model="stopLoss.step" size="small" placeholder="步长" />
            <el-checkbox v-model="stopLoss.enabled">启用</el-checkbox>
          </div>
        </div>

        <div class="param-row">
          <div class="param-label">止盈比例</div>
          <div class="param-inputs">
            <el-input v-model="takeProfit.min" size="small" placeholder="最小值" />
            <el-input v-model="takeProfit.max" size="small" placeholder="最大值" />
            <el-input v-model="takeProfit.step" size="small" placeholder="步长" />
            <el-checkbox v-model="takeProfit.enabled">启用</el-checkbox>
          </div>
        </div>
      </div>

      <div class="optimization-result">
        <div class="section-title">优化结果</div>
        <div class="scatter-plot" ref="scatterPlot"></div>
        
        <div class="result-table">
          <el-table :data="optimizationResults" style="width: 100%" size="small">
            <el-table-column prop="params" label="参数组合" />
            <el-table-column prop="returnRate" label="收益率">
              <template slot-scope="scope">
                <span :class="{'positive': scope.row.returnRate > 0}">{{scope.row.returnRate}}%</span>
              </template>
            </el-table-column>
            <el-table-column prop="sharpeRatio" label="夏普比率" />
            <el-table-column prop="maxDrawdown" label="最大回撤">
              <template slot-scope="scope">
                <span class="negative">{{scope.row.maxDrawdown}}%</span>
              </template>
            </el-table-column>
            <el-table-column prop="winRate" label="胜率">
              <template slot-scope="scope">{{scope.row.winRate}}%</template>
            </el-table-column>
            <el-table-column prop="trades" label="交易次数" />
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="success" size="mini" @click="applyParams(scope.row)">应用</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import _ from 'lodash'

export default {
  name: 'StrategyOptimization',
  data() {
    return {
      selectedStrategy: '',
      backTestPeriod: '30',
      optimizationTarget: 'maxProfit',
      fastMA: {
        min: '10',
        max: '30',
        step: '5',
        enabled: true
      },
      slowMA: {
        min: '30',
        max: '100',
        step: '10',
        enabled: true
      },
      stopLoss: {
        min: '1',
        max: '5',
        step: '0.5',
        enabled: true
      },
      takeProfit: {
        min: '2',
        max: '10',
        step: '1',
        enabled: true
      },
      scatterChart: null,
      resizeObserver: null,
      chartOption: null,
      optimizationResults: [
        {
          params: 'MA(15,50), SL:2%, TP:5%',
          returnRate: 24.6,
          sharpeRatio: 2.45,
          maxDrawdown: -8.2,
          winRate: 71.3,
          trades: 82
        },
        {
          params: 'MA(20,60), SL:2.5%, TP:6%',
          returnRate: 22.1,
          sharpeRatio: 2.32,
          maxDrawdown: -7.5,
          winRate: 68.9,
          trades: 75
        },
        {
          params: 'MA(10,40), SL:1.5%, TP:4%',
          returnRate: 19.8,
          sharpeRatio: 2.12,
          maxDrawdown: -9.1,
          winRate: 72.6,
          trades: 94
        },
        {
          params: 'MA(25,75), SL:3%, TP:7%',
          returnRate: 18.4,
          sharpeRatio: 2.05,
          maxDrawdown: -6.8,
          winRate: 65.2,
          trades: 64
        },
        {
          params: 'MA(20,80), SL:2%, TP:8%',
          returnRate: 16.9,
          sharpeRatio: 1.98,
          maxDrawdown: -7.2,
          winRate: 67.8,
          trades: 72
        }
      ]
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
      this.initResizeObserver()
      window.addEventListener('resize', this.handleResize)
    })
  },
  beforeDestroy() {
    if (this.resizeObserver) {
      this.resizeObserver.disconnect()
    }
    window.removeEventListener('resize', this.handleResize)
    if (this.scatterChart) {
      this.scatterChart.dispose()
    }
  },
  methods: {
    initChart() {
      if (!this.$refs.scatterPlot) return

      // 确保容器有正确的尺寸
      const container = this.$refs.scatterPlot
      if (container.offsetWidth === 0) {
        setTimeout(() => this.initChart(), 100)
        return
      }

      // 初始化图表
      if (!this.scatterChart) {
        this.scatterChart = echarts.init(container, null, {
          renderer: 'canvas',
          width: 'auto',
          height: 'auto'
        })
      }

      // 生成散点图数据
      const data = []
      for (let i = 0; i < 50; i++) {
        data.push([
          Math.random() * 100,
          Math.random() * 100,
          Math.random() * 100,
          ['低风险', '中风险', '高风险'][Math.floor(Math.random() * 3)]
        ])
      }

      // 保存图表配置
      this.chartOption = {
        grid: {
          top: 40,
          right: 40,
          bottom: 60,
          left: 60,
          containLabel: true
        },
        tooltip: {
          trigger: 'item',
          formatter: function(params) {
            return `收益率: ${params.value[0].toFixed(2)}%<br/>
                    夏普比: ${params.value[1].toFixed(2)}<br/>
                    最大回撤: ${params.value[2].toFixed(2)}%<br/>
                    风险等级: ${params.value[3]}`
          }
        },
        xAxis: {
          type: 'value',
          name: '收益率',
          nameLocation: 'center',
          nameGap: 30,
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#E4E7ED'
            }
          },
          axisLine: {
            lineStyle: {
              color: '#909399'
            }
          },
          axisLabel: {
            formatter: '{value}%'
          }
        },
        yAxis: {
          type: 'value',
          name: '夏普比率',
          nameLocation: 'center',
          nameGap: 30,
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#E4E7ED'
            }
          },
          axisLine: {
            lineStyle: {
              color: '#909399'
            }
          }
        },
        series: [{
          type: 'scatter',
          data: data,
          symbolSize: function(data) {
            return Math.sqrt(data[2]) * 3
          },
          itemStyle: {
            color: function(params) {
              const colors = {
                '低风险': '#67C23A',
                '中风险': '#E6A23C',
                '高风险': '#F56C6C'
              }
              return colors[params.data[3]]
            }
          }
        }]
      }

      // 设置图表配置
      this.scatterChart.setOption(this.chartOption)
    },
    initResizeObserver() {
      // 使用ResizeObserver监听容器大小变化
      this.resizeObserver = new ResizeObserver(entries => {
        entries.forEach(entry => {
          if (entry.target === this.$refs.scatterPlot) {
            this.handleResize()
          }
        })
      })

      if (this.$refs.scatterPlot) {
        this.resizeObserver.observe(this.$refs.scatterPlot)
      }
    },
    handleResize: _.debounce(function() {
      if (this.scatterChart && this.$refs.scatterPlot) {
        const container = this.$refs.scatterPlot
        const width = container.offsetWidth
        const height = container.offsetHeight

        if (width > 0 && height > 0) {
          this.scatterChart.resize({
            width: width,
            height: height
          })
        }
      }
    }, 200),
    startOptimization() {
      // 开始优化逻辑
      this.$message.success('开始参数优化...')
    },
    applyParams(row) {
      // 应用参数逻辑
      this.$message.success(`应用参数组合: ${row.params}`)
    }
  }
}
</script>

<style lang="scss" scoped>
.optimization-container {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

  .optimization-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .title {
      font-size: 16px;
      font-weight: 500;
      color: #303133;
    }

    .actions {
      display: flex;
      gap: 12px;
      align-items: center;

      .el-select {
        width: 160px;
      }
    }
  }

  .optimization-content {
    .param-section {
      background: #F8F9FA;
      border-radius: 8px;
      padding: 20px;
      margin-bottom: 20px;

      .section-row {
        display: flex;
        align-items: center;
        margin-bottom: 16px;

        &:last-child {
          margin-bottom: 0;
        }

        .label {
          width: 80px;
          color: #606266;
          font-size: 14px;
        }

        .el-select {
          width: 200px;
        }
      }

      .section-title {
        font-size: 14px;
        font-weight: 500;
        color: #303133;
        margin-bottom: 16px;
      }

      .param-row {
        display: flex;
        align-items: center;
        margin-bottom: 16px;

        &:last-child {
          margin-bottom: 0;
        }

        .param-label {
          width: 160px;
          color: #606266;
          font-size: 14px;
        }

        .param-inputs {
          display: flex;
          gap: 12px;
          align-items: center;
          flex: 1;

          .el-input {
            width: 100px;
          }
        }
      }
    }

    .optimization-result {
      .section-title {
        font-size: 14px;
        font-weight: 500;
        color: #303133;
        margin-bottom: 16px;
      }

      .scatter-plot {
        width: 100%;
        height: 300px;
        margin-bottom: 20px;
      }

      .result-table {
        .positive {
          color: #67C23A;
        }

        .negative {
          color: #F56C6C;
        }
      }
    }
  }
}

// 覆盖element-ui的一些默认样式
:deep(.el-table) {
  margin-top: 16px;

  th {
    background-color: #F8F9FA !important;
    color: #606266;
    font-weight: 500;
  }
}

:deep(.el-button--success) {
  padding: 5px 12px;
}
</style> 